package com.ncss.http.proxy.server.handler;

import com.ncss.http.proxy.server.CloseUtils;
import com.ncss.http.proxy.server.Parameters;

import java.io.*;
import java.net.*;
import java.util.Map;

public class CacheImageHandler {

    private Parameters parameters;

    private Map<String, String> headers;

    public CacheImageHandler(Parameters parameters) {

        this.parameters = parameters;

    }

    public CacheImageHandler(Parameters parameters, Map<String, String> headers) {

        this.parameters = parameters;
        this.headers = headers;
    }

    public File handle() {
        InputStream in = null;
        OutputStream out = null;
        try {
            File file = this.creatFilePath(parameters);
            if (!file.exists()) {
                //String urlList = String.format("http://shangetu1.map.bdimg.com/it/u=x=%s;y=%s;z=%s;v=009;type=sate&fm=46&udt=20130506", parameters.getX(), parameters.getY(), parameters.getY());
                //String urlList  ="http://d3.map.baidu.com/resource/mappic/bj/2/3/lv2/1251,1143.jpg?v=001";
                String urlList = parameters.getUrl().replace("{x}", parameters.getX());
                urlList = urlList.replace("{y}", parameters.getY());
                urlList = urlList.replace("{z}", parameters.getZ());


                //String urlList  =String.format("http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/%s/%s/%s",parameters.getZ(),parameters.getY(),parameters.getX());
                //String urlList  =String.format("http://tiles.windy.com/tiles/v8.1/darkmap/%s/%s/%s.png",parameters.getZ(),parameters.getX(),parameters.getY());
                URL url = new URL(urlList);
                SocketAddress sa = new InetSocketAddress("127.0.0.1", 1080);
                Proxy proxy = new Proxy(Proxy.Type.HTTP, sa);
                HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(proxy);
                System.out.println("connect to url " + url);
                httpUrlConn.setDoInput(true);
                httpUrlConn.setRequestMethod("GET");
                httpUrlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
                httpUrlConn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
                httpUrlConn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
                httpUrlConn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.9");
                httpUrlConn.setRequestProperty("Upgrade-Insecure-Requests", "1");
                //httpUrlConn.setRequestProperty("Host","tiles.windy.com");
                //httpUrlConn.setRequestProperty("scheme", "https");
                //httpUrlConn.setRequestProperty("authority", "mt1.google.cn");
                //httpUrlConn.setRequestProperty("x-client-data", "CKu1yQEIiLbJAQiktskBCMS2yQEIipLKAQipncoBCNidygEIqKPKAQiCpMoB");
                //httpUrlConn.setRequestProperty("path", String.format("/vt/lyrs=t&hl=zh-CN&gl=cn&x=%s0&y=%s&z=%s", parameters.getX(), parameters.getY(), parameters.getY()));
                //url.openConnection().getOutputStream().
                int code = httpUrlConn.getResponseCode();
                System.out.println("code ==" + code);
                in = httpUrlConn.getInputStream();
                out = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = in.read(buffer)) > 0) {
                    out.write(buffer, 0, length);
                    out.flush();
                }
            }
            return file;
        } catch (BindException e2) {
            return this.handle();
        } catch (Exception e) {
            System.err.println("got error." + e.getMessage());
            e.printStackTrace();
            return null;
        } finally {
            CloseUtils.close(in);
        }
    }


    public File creatFilePath(Parameters parameters) {
        File file = new File(String.format("%s/%s/%s", parameters.getFilePath(), parameters.getZ(), parameters.getY()));
        if (!file.exists()) {
            file.mkdirs();
        }
        file = new File(file.getPath() + '/' + parameters.getX() + ".png");
        return file;
    }

    public static void main(String[] args) {
        System.out.println(Math.pow(2, 18));
    }
}
